import { useStore } from 'vuex'
import { computed, ref, watch } from 'vue'

export default function useCd () {
  const cdRef = ref(null)
  const cdImageRef = ref(null)
  const store = useStore()
  const playing = computed(() => store.state.isPlaying)
  const cdClass = computed(() => {
    return playing.value ? 'playing' : ''
  })

  // 监听playing，如果暂停状态，则记录当前旋转角度赋给cdRef，使两者相对静止
  watch(playing, (newPlaying) => {
    if (!newPlaying) {
      syncTransform(cdRef.value, cdImageRef.value)
    }
  })

  // 同步transform
  function syncTransform (wrapper, inner) {
    const wrapperTransform = getComputedStyle(wrapper).transform
    const innerTransform = getComputedStyle(inner).transform
    // 内层的旋转角度是相对于外层的，因此需要将旋转角度做叠加
    wrapper.style.transform = wrapperTransform === 'none' ? innerTransform : innerTransform + wrapperTransform
  }
  return {
    cdRef,
    cdImageRef,
    cdClass
  }
}
